package main

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"flag"
	"golang.org/x/crypto/pkcs12"
	"io/ioutil"
	"log"
)

var (
	p12CertPath = ""
	passwd      = ""
)

func init() {
	flag.StringVar(&p12CertPath, "P12", "client.p12", "P12文件")
	flag.StringVar(&passwd, "pw", "zhang1978", "P12文件")
}
func main() {
	flag.Parse()

	p12Cert, err := ioutil.ReadFile(p12CertPath)
	pemBlock, err := pkcs12.ToPEM(p12Cert, passwd)

	cert, err := tls.X509KeyPair(pem.EncodeToMemory(pemBlock[0]), pem.EncodeToMemory(pemBlock[1]))
	//cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
	if err != nil {
		log.Println(err)
		return
	}

	pool := x509.NewCertPool()

	caCertPath := "ca.crt"
	caCrt, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		log.Panicln("ReadFile err:", err)
	}
	if ok := pool.AppendCertsFromPEM(caCrt); !ok {
		log.Panicln("failed to parse root certificate")
	}

	conf := &tls.Config{
		RootCAs:      pool,
		Certificates: []tls.Certificate{cert},
		//是否校验证书:
		// true 放弃校验服务段证书，
		// false 如果要校验私有证书，必须导入CA证书。且必须符合extfile文件的规则
		InsecureSkipVerify: false,
	}
	//conn, err := tls.Dial("tcp", "10.21.57.71:1443", conf)
	conn, err := tls.Dial("tcp", "127.0.0.1:1443", conf)
	if err != nil {
		log.Println(err)
		return
	}
	log.Println(conn.ConnectionState().PeerCertificates[0])
	defer conn.Close()
	n, err := conn.Write([]byte("hello\n"))
	if err != nil {
		log.Println(n, err)
		return
	}
	buf := make([]byte, 100)
	n, err = conn.Read(buf)
	if err != nil {
		log.Println(n, err)
		return
	}
	println(string(buf[:n]))
}
